# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import sys
import hashlib
import base64

import datetime
import Environment
from web_lib.page import Page
from web_lib.webutils import Response, expose, change_schema
import json
from lib.utils import *
from dao.Ente import Ente


@expose('/opendatajsonsubmit')
def opendatajsonsubmit(req):
    """ Questa funzione permette di gestire il ritorno dei dati dalla
    app mobile.
    """
    #print " REQ FORM", str(req.form.items()[0][0])
    #dati= json.loads(str(req.form.items()[0][0]))
    #print "dati", dati["name"]
    codice = req.form.get("codice")
    print "DATI DELLA REQUEST", req.form.to_dict()
    if codice:
        comune = Ente().select(codice=codice)
        sch = comune[0].denominazione_breve.lower().replace(" ", "")
        Environment.sch = sch
        Environment.census = True
        change_schema(req, sch, app=True)
        from dao.OpenData import OpenData
        from dao.Categoria import Categoria
        from dao.Campo import Campo
        from dao.Operatore import Operatore
        cate = int(req.form.get("id"))
        categoria = Categoria().getRecord(id=cate)
        operKey =  req.form.get("operKey")
        operId = None
        if operKey and operKey != "" and operKey != "None":
            d = Operatore().select(passwordKey=operKey)
            if d:
                operId = d[0].id
        objson = req.form.get("objson")
        a = OpenData()
        a.id_categoria = categoria.id
        a.id_operatore = operId
        a.objson = objson or "[{}]"
        has_record = hashlib.sha224(str(a.objson)).hexdigest()
        odd = OpenData().select(hash_record=has_record, batchSize=None)
        if not odd:
            a.hash_record = has_record
        #da = json.loads(a.objson)
        a.id_ente = comune[0].id
        a.data_inserimento = datetime.datetime.now()
        #print a.__dict__
        a.persist()
        item = {"Result":"OK", "Reason": "",}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        Environment.sch = None
        Environment.census = False
        return Response(jasoned)
    else:
        pageData = {'file' : "/pg/index",
                    "msg":"NON E' IL MODO GIUSTO DI ACCEDERE A QUESTA PAGINA"}
        return Page(req).render(pageData)


@expose('/operatoreInsert')
def operatoreSet(req):
    """ Questa funzione permette di gestire il ritorno dei dati dalla
    app mobile.
    Column('username', String(50), nullable=False),
    Column('password', String(50), nullable=False),
    Column('email', String(70), nullable=True),
    Column('cognome', String(70), nullable=True),
    Column('nome', String(70), nullable=True),
    Column('registration_date', DateTime,ColumnDefault(datetime.datetime.now)),
    Column('last_modified', DateTime),
    Column('photo', Text, nullable=True),
    Column('icona', Text, nullable=True),
    Column('cellulare', String(50), nullable=True),
    Column('f_qrcode', Text, nullable=True),
    Column('f_ean', Text, nullable=True),
    Column('f_imei', String(50), nullable=True),
    Column('f_idreg', String(50), nullable=True),
    Column('data_nascita', DateTime),
    Column('active', Boolean, default=False),
    Column('tipo_operatore', String(50), nullable=True),
    Column('genere', String(10), nullable=True),
    Column('privacy', Boolean, default=False),
    Column('mailing_list', Boolean, default=False),
    """
    #print "dati", dati["name"]
    codice = req.form.get("codice")
    #print "DATI DELLA REQUEST FORM", req.form.to_dict()
    #print "DALLA DELLA REQUEST ARGS", req.args.to_dict()
    if codice:
        comune = Ente().select(codice=codice)
        sch = comune[0].denominazione_breve.lower().replace(" ", "")
        Environment.sch = sch
        Environment.census = True
        change_schema(req, sch, app=True)
        from dao.Operatore import Operatore
        objson = req.form.get("objson")
        #print " OOOOOOOOOOOOOBB", objson
        d = json.loads(objson)
        print " DICT JSON", d[0]
        a = Operatore()
        username = d[0]["cognome"] + "." + d[0]["nome"]
        a.username = username.lower()
        passwd = hashlib.md5(username.lower() + str(d[0]["email"])).hexdigest()
        a.password = passwd
        a.email = d[0]["email"]
        a.cognome = d[0]["cognome"]
        a.nome = d[0]["nome"]
        a.registration_date = datetime.datetime.now()
        #a.last_modified =
        #a.photo =
        #a.icona =
        a.cellulare = d[0]["cellulare"]
        a.f_imei = d[0]["f_imei"]
        a.data_nascita = stringToDate(d[0]["data_nascita"])
        a.active = True
        a.tipo_operatore = "cliente"
        a.genere = d[0]["genere"] if "genere" in d[0] else "M"
        a.privacy = bool(d[0]["privacy"])
        a.mailing_list = bool(d[0]["mailing_list"])
        stringa= "Cognome: " + str(a.cognome or "") + "\n" + \
                    "Nome: " + str(a.nome or "") + "\n" + \
                    "Email: " + str(a.email or "") + "\n"+ \
                    "Cellulare: " + str(a.cellulare or "") + "\n" + \
                    "Codice: " + str(a.password[0:10])
        data = createbarcode(a.password[0:10])
        if data:
            a.f_ean = base64.b64encode(data)
        dataqrcode = createbarcodeqr(stringa)
        if dataqrcode:
            a.f_qrcode = base64.b64encode(dataqrcode)

        a.persist()
        item = {"Result":"OK",
                "operKey": passwd[0:10] ,}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        Environment.sch = None
        Environment.census = False
        return Response(jasoned)
    else:
        pageData = {'file' : "/pg/index",
                    "msg":"NON E' IL MODO GIUSTO DI ACCEDERE A QUESTA PAGINA"}
        return Page(req).render(pageData)


@expose('/getSetupCensus')
def getSetupCensus(req):
    """Questa funzione permette di prelevare i dati e le
    informazioni necessarie alla ui census"""
    #print "DALLA DELLA REQUEST", req.form.to_dict()
    codice = req.form.get("codice")
    #print "POST", codice, type(codice)
    if not codice:
        codice = req.args.get("codice")
        #print "GET", codice
    if not codice:
        return Response("{}")
    comune = Ente().select(codice=codice)
    comu = []
    if not comune:
        item = {
            "Result":"ERROR",
            "codice":"",
            "skeleton" : {},
            "nomi_cataloghi":[]
            }
        jasoned = json.dumps(item,sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False, encoding='utf8')
        #print "JASON", jasoned
        return Response(jasoned)
    else:
        sch = comune[0].denominazione_breve.lower().replace(" ", "")
        Environment.sch = sch
        Environment.census = True
        change_schema(req, sch, app=True)
        comune_ = prep2json(comune[0])
        comu.append(comune_)
        from dao.EnteCategoria import EnteCategoria
        from dao.CategoriaCampo import CategoriaCampo
        gendict= {}
        cataloghi = [m.categoria.tipo_categoria for m in EnteCategoria().select(id_ente=comune[0].id)]
        cats = list(set(cataloghi))
        cata = []
        catadict = {}
        for ca in cats:
            categorie = []
            categoriedict = {}
            pp = 0
            for c in EnteCategoria().select(id_ente=comune[0].id):
                if c.categoria.tipo_categoria == ca:
                    pp = pp + 1
                    categorie.append(prep2json(c.categoria))
                    campo = []
                    campodict = {}
                    for d in CategoriaCampo().select(id_categoria=c.categoria.id):
                    #for d in c.categoria.categoriacampo:
                        campo.append(prep2json(d.campo))
                    campodict["ncampi"] = len(c.categoria.categoriacampo)
                    campodict["campi"] = campo
                    categorie.append (campodict)
                categoriedict["categoria"] = categorie
                categoriedict["ncategorie"] = pp
                #categoriedict["icona_catalogo"] = ca.icona_catalogo
            catadict[ca] = categoriedict
        cata.append(catadict)

        gendict["cataloghi"] = cata
        comu.append(gendict)
        #comu.append(cats)
    d = {"ente":comu}

    item = {
            "Result":"OK",
            "codice":codice,
            "skeleton" : d,
            "nomi_cataloghi":cats
            }
    jasoned = json.dumps(item,sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False, encoding='utf8')
    #print "JASON", jasoned
    Environment.sch = None
    Environment.census = False
    return Response(jasoned)
